<script lang="ts" setup>
import { defineComponent, h, nextTick, reactive, ref, useTemplateRef } from 'vue'
import { ElInput } from 'element-plus'
import type { Ref } from 'vue'

interface Student {
  id: number
  name: string
  age: number
  sex: string
  address: string
}
const tableData = reactive<Student[]>([
  {
    id: 1,
    name: '王五',
    age: 20,
    sex: '男',
    address: '北京市'
  },
  {
    id: 2,
    name: '张三',
    age: 18,
    sex: '',
    address: '开鲁县'
  },
  {
    id: 3,
    name: '李四',
    age: 19,
    sex: '男',
    address: '通辽市'
  }
])
const EditIpt = defineComponent({
  name: 'EditIpt',
  props: {
    value: {
      type: [Number, String]
    }
  },
  emits: ['changeValue'],
  setup(props, { emit }) {
    const isEdit = ref(false)
    const inputRef = useTemplateRef('inputRef') as Ref<HTMLInputElement>
    async function handleOnClick() {
      isEdit.value = true
      await nextTick()
      inputRef.value?.focus()
    }
    return () =>
      h(
        'div',
        {
          onClick: handleOnClick,
          style: {
            width: '100%'
          }
        },
        [
          isEdit.value
            ? h(ElInput, {
                ref: 'inputRef',
                modelValue: props.value,
                onInput(v) {
                  emit('changeValue', v)
                },
                onBlur() {
                  isEdit.value = false
                }
              })
            : props.value || '\u3000'
        ]
      )
  }
})
const tableEditRef = useTemplateRef('tableEditRef')
const tableConfigEdit = reactive<TableConfig<Student>>({
  columns: [
    {
      type: 'default',
      label: '姓名',
      prop: 'name',
      defaultCell(props) {
        return h(ElInput, {
          modelValue: props.row.name,
          onInput(v) {
            props.row.name = v
          }
        })
      }
    },
    {
      type: 'default',
      label: '年龄',
      prop: 'age',
      defaultCell(props) {
        return h(EditIpt, {
          value: props.row.age,
          onChangeValue(v: number) {
            props.row.age = v
          }
        })
      }
    },
    {
      label: '操作',
      type: 'operate',
      width: 230,
      buttons: props => [
        {
          label: '提交',
          isShow: props.row.age < 19,
          text: true,
          click: async props => {
            const tableData = await tableEditRef.value?.tableRef?.validate?.({ rows: props.$index })
            console.log(tableData)
          }
        },
        {
          label: '删除',
          type: 'primary',
          click: props => {
            console.log(props)
          }
        }
      ]
    }
  ]
})
</script>
<template>
  <XyTable ref="tableEditRef" :tableConfig="tableConfigEdit" :tableData="tableData" />
</template>
